package org.groupg.demo.sshd;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.ClientChannelEvent;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;

public class SshClientExample {
    public static void main(String[] args) throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();

        try (ClientSession session = client.connect("username", "hostname", 22)
                .verify(5000, TimeUnit.MILLISECONDS)
                .getSession()) {

            session.addPasswordIdentity("password");
            session.auth().verify(5000, TimeUnit.MILLISECONDS);

            try (ByteArrayOutputStream out = new ByteArrayOutputStream();
                 ByteArrayOutputStream err = new ByteArrayOutputStream();
                 ClientChannel channel = session.createChannel("exec", "ls -l")) {

                channel.setOut(out);
                channel.setErr(err);
                channel.open().verify(5000, TimeUnit.MILLISECONDS);
                channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);

                System.out.println("Output: " + out.toString());
                System.out.println("Error: " + err.toString());
            }
        } finally {
            client.stop();
        }
    }
}